<?php
namespace Common\Model;

use Think\Model;
use Common\Model\OpenIdModel as OpenId;
use Common\Model\ConfigModel as Config;
use Com\Weixin\WeixinApi as WeixinApi;
use Common\Model\FansModel as Fans;
use Fenxiao\Model\FeedModel as Feed;

class UserModel extends Model
{

    protected $tableName = 'user';

    /**
     * 新增用户信息
     * 
     * @param unknown $add            
     */
    public function addUser($add)
    {
        $config = new Config();
        $union_mode = $config->getConfig("UNION_MODE");
        
        if ($union_mode == 1)
        {
            $where = array();
            $where['union_id'] = $add['union_id'];
            $is_exist = $this->where($where)->find();
        } else if ($add['openid'])
        {
            $where = array();
            $where['openid'] = $add['openid'];
            $is_exist = $this->where($where)->find();
        } else
        {
            return false;
        }
        
        // 新增
        if (! $is_exist)
        {
            $add['updatetime'] = date('Y-m-d H:i:s');
            $add['flag'] = $add['flag'] ? $add['flag'] : 0;
            $add['state'] = $add['state'] == 1 ? 1 : 0;
            
            $uid = $this->add($add);
        } else if ($is_exist)
        {
            $uid = $is_exist['id'];
            
            $where = array();
            $where['id'] = $uid;
            
            foreach ($add as $item => $key)
            {
                if (! isset($key))
                {
                    unset($add[$item]);
                }
            }
            
            $update = $add;
            $update['updatetime'] = date('Y-m-d H:i:s');
            
            $this->where($where)->save($update);
        } else
        {
            return false;
        }
        
        if ($uid && $add['openid'])
        {
            $open_obj = new OpenId();
            $uu = $open_obj->openid2Uid($add['openid']);
            // 新增 openid
            if (! $uu)
            {
                $new = array();
                $new['uid'] = $uid;
                $new['openid'] = $add['openid'];
                $new['wxhao'] = C('WX_HAO');
                $new['updatetime'] = date('Y-m-d H:i:s');
                $new['state'] = $add['state'] == 1 ? 1 : 0;
                
                $open_obj->add($new);
            } else
            {
                $update2 = array();
                $update2['state'] = $add['state']==1 ? 1 : 0;
                $update2['updatetime'] = date('Y-m-d H:i:s');
            }
        }
        
        // 新增情况，分配邀请码
        if ($uid && ! $is_exist)
        {
            $where = array();
            $where['id'] = $uid;
            
            $uid_len = strlen($uid);
            $uid_len = $uid_len + 1;
            $uid_len = $uid_len < 6 ? 6 : $uid_len;
            
            $update = array();
            $len = $uid_len - strlen($uid);
            
            $update['code'] = $this->code($uid);
            if ($update2)
            {
                $update = array_merge($update, $update2);
            }
            
            $rs = $this->where($where)->save($update);
            
            if (false === $rs)
            {
                my_log("add code fail:" . $this->getLastSql());
            }
        }
        
        return $uid;
    }

    private function code($uid, $level = 0, $special = false)
    {
        global $arr, $c;
        
        if ($level >= 10)
        {
            return "";
        }
        
        if (! $special)
        {
            // 判断是否靓号
            $save = array(
                '111',
                '222',
                '333',
                '444',
                '555',
                '666',
                '777',
                '888',
                '999',
                '000',
                '01234',
                '12345',
                '23456',
                '34567',
                '45678',
                '56789'
            );
            foreach ($save as $key => $value)
            {
                $r = strstr($uid, $value);
                if ($r)
                {
                    $special = true;
                    break;
                }
            }
        }
        
        $letter2 = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
        
        if ($special)
        {
            $tmp = '';
            for ($i = 0; $i < 6; $i ++)
            {
                $l = strlen($letter2) - 1;
                $index = mt_rand(0, $l);
                $tmp .= $letter2[$index];
            }
        } else
        {
            $tmp = dechex($uid);
            $l = 6 - strlen($tmp);
            if ($l > 0)
            {
                $prefix = '';
                for ($i = 0; $i < $l; $i ++)
                {
                    $ll = strlen($letter2) - 1;
                    $index = mt_rand(0, $ll);
                    $prefix .= $letter2[$index];
                }
                
                $tmp = str_pad($tmp, 6, 'F');
            } else if ($l == 0 && $level > 0)
            {
                $prefix = substr($uid, 0, 5);
                $ll = strlen($letter2) - 1;
                $index = mt_rand(0, $ll);
                $ext = $letter2[$index];
                $tmp = $prefix . $ext;
            }
        }
        
        $tmp = strtoupper($tmp);
        if (isset($arr[$tmp]))
        {
            
            $c ++;
            $level = $level + 1;
            
            return $this->code($uid, $level, $special);
        }
        
        return $tmp;
    }

    /**
     * 获取用户详细信息，并且入库
     *
     * @param unknown $openid            
     */
    public function getWeixinUserDetailInfo($openid)
    {
        $weixin_obj = new WeixinApi();
        
        $access_token = $weixin_obj->getToken();
        if ($access_token)
        {
            $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
            $rs1 = https_request($url);
            
            if ($rs1 === false)
            {
                my_log('get url fail:' . $url);
                return false;
            }
            
            $rs_obj = json_decode($rs1);
            $rs = objToArr($rs_obj);
            
            if (empty($rs) && json_last_error() != 0)
            {
                $str = substr(str_replace('\"', '"', json_encode($rs1, JSON_UNESCAPED_UNICODE)), 1, - 1);
                $rs = json_decode($str, true);
                $rs['headimgurl'] = str_replace('\\', "", $rs['headimgurl']);
            }
            
            if (is_array($rs) && ! empty($rs['openid']))
            {
                
                $update = array();
                $update['logo'] = $userInfo['logo'] = $rs['headimgurl'];
                $update['nickname'] = $userInfo['nickname'] = $rs['nickname'];
                
                $update['sex'] = $rs['sex'];
                $update['language'] = $rs['language'];
                $update['city'] = $rs['city'];
                $update['province'] = $rs['province'];
                $update['country'] = $rs['country'];
                $update['union_id'] = $rs['unionid'];
                
                return $update;
            } else
            {
                my_log('getUserDetailInfo fail:' . $rs1 . ' . access_token:' . $access_token . '.openid:' . $openid . '.error code:' . json_last_error());
            }
        } else
        {
            my_log('get token error :' . $access_token);
        }
        
        return false;
    }


    /**
     * 获取用户详细信息，并且入库(通过网页授权的，用户可以没有关注)
     *
     * @param unknown $openid
     */
    public function getWeixinUserDetailInfo2($openid,$access_token)
    {
    
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $rs1 = https_request($url);
    
        if ($rs1 === false)
        {
            my_log('get url fail:' . $url);
            return false;
        }
    
        $rs_obj = json_decode($rs1);
        $rs = objToArr($rs_obj);
    
        if (empty($rs) && json_last_error() != 0)
        {
            $str = substr(str_replace('\"', '"', json_encode($rs1, JSON_UNESCAPED_UNICODE)), 1, - 1);
            $rs = json_decode($str, true);
            $rs['headimgurl'] = str_replace('\\', "", $rs['headimgurl']);
        }
    
        if (is_array($rs) && ! empty($rs['openid']))
        {
    
            $update = array();
            $update['logo'] = $userInfo['logo'] = $rs['headimgurl'];
            $update['nickname'] = $userInfo['nickname'] = $rs['nickname'];
    
            $update['sex'] = $rs['sex'];
            $update['language'] = $rs['language'];
            $update['city'] = $rs['city'];
            $update['province'] = $rs['province'];
            $update['country'] = $rs['country'];
            $update['union_id'] = $rs['unionid'];
    
            return $update;
        } else
        {
            my_log('getUserDetailInfo fail:' . $rs1 . ' . access_token:' . $access_token . '.openid:' . $openid . '.error code:' . json_last_error());
        }
    
    
        return false;
    }
    
    
    /**
     * 添加粉丝关系
     * 
     * @param unknown $tuiguangCode            
     * @param unknown $uid            
     * @param number $source
     *            1|2|3 来源
     * @return boolean
     */
    function addFans($tuiguangCode, $uid, $source = 3)
    {
        try
        {
            $model = new Model();
            $u = $this;
            $fans = new Fans();
            
            $where = array();
            $where['id'] = $uid;
            $u_data = $u->getUserById($uid);
            if (empty($u_data) || $u_data['flag'] == 1)
            {
                return false;
            }
            
            $model->startTrans();
            
            $where = array();
            $where['code3'] = $tuiguangCode;
            // $where['id'] = $tuiguangCode;
            // $where['_logic'] = 'OR';
            
            $p_user = $u->where($where)->find();
            
            if (! $p_user)
            {
                return false;
            }
            
            if ($p_user['id'] == $uid)
            {
                return false;
            }
            
            if ($p_user['level'] < 0)
            {
                E('非会员不能加关注', 400);
            }
            
            // 一级粉丝
            
            $data = array();
            $data['userid'] = $p_user['id'];
            $data['fansid'] = $uid;
            $data['level'] = 1;
            $data['source'] = $source;
            $data['status'] = 0;
            $add_rs1 = $fans->add($data);
            if (! $add_rs1)
            {
                E('添加1级粉丝失败', 500);
            }
            // 二级粉丝
            $where = array();
            $where['fansid'] = $p_user['id'];
            $erji = $fans->where($where)->find();
            
            if ($erji)
            {
                if ($erji['level'] >= 0)
                {
                    
                    if ($erji['userid'] != $uid && $p_user['id'] != $erji['userid'])
                    {
                        $data = array();
                        $data['userid'] = $erji['userid'];
                        $data['fansid'] = $uid;
                        $data['level'] = 2;
                        $data['source'] = $source;
                        $data['status'] = 0;
                        $add_rs2 = $fans->add($data);
                        if (! $add_rs2)
                        {
                            E('添加2级粉丝失败', 500);
                        }
                    }
                }
            }
            
            // 三级粉丝
            if ($erji)
            {
                $where = array();
                $where['fansid'] = $erji['userid'];
                $sanji = $fans->where($where)->find();
                
                if ($sanji)
                {
                    if ($sanji['level'] >= 0)
                    {
                        if ($sanji['userid'] != $uid && $sanji['userid'] != $erji['userid'] && $sanji['userid'] != $p_user['id'])
                        {
                            $data = array();
                            $data['userid'] = $sanji['userid'];
                            $data['fansid'] = $uid;
                            $data['level'] = 3;
                            $data['source'] = $source;
                            $data['status'] = 0;
                            $add_rs3 = $fans->add($data);
                            if (! $add_rs3)
                            {
                                E('添加3级粉丝失败', 500);
                            }
                        }
                    }
                }
            }
            
            // 查看当前用户的一级粉丝，是否可以成为当前用户父亲的2级粉丝
            $first_fans = $fans->getFansByUidAndLevel($uid, 1);
            if ($first_fans && $p_user)
            {
                foreach ($first_fans as $fans_item)
                {
                    $data = array();
                    $data['userid'] = $p_user['id'];
                    $data['fansid'] = $fans_item['fansid'];
                    $data['level'] = 2;
                    $data['source'] = $source;
                    $data['status'] = 0;
                    $add_rs3 = $fans->add($data);
                    if (! $add_rs3)
                    {
                        E('添加当前用户的一级粉丝成为当前用户父亲的2级粉丝失败', 500);
                    }
                }
            }
            // 查看当前用户的一级粉丝，是否可以成为当前用户爷爷的3级粉丝
            if ($first_fans && $erji)
            {
                foreach ($first_fans as $fans_item)
                {
                    $data = array();
                    $data['userid'] = $erji['userid'];
                    $data['fansid'] = $fans_item['fansid'];
                    $data['level'] = 3;
                    $data['source'] = $source;
                    $data['status'] = 0;
                    $add_rs3 = $fans->add($data);
                    if (! $add_rs3)
                    {
                        E('添加当前用户的一级粉丝成为当前用户爷爷的3级粉丝失败', 500);
                    }
                }
            }
            
            // 查看当前用户的二级粉丝，是否可以成为当前用户父亲的3级粉丝
            $second_fans = $fans->getFansByUidAndLevel($uid, 2);
            if ($second_fans && $p_user)
            {
                foreach ($second_fans as $second_item)
                {
                    $data = array();
                    $data['userid'] = $p_user['id'];
                    $data['fansid'] = $second_item['fansid'];
                    $data['level'] = 3;
                    $data['source'] = $source;
                    $data['status'] = 0;
                    $add_rs3 = $fans->add($data);
                    if (! $add_rs3)
                    {
                        E('添加当前用户的二级粉丝成为当前用户父亲的3级粉丝失败', 500);
                    }
                }
            }
            
            // 更新推广位标志位
            $where = array();
            $where['id'] = $uid;
            $data = array();
            $data['flag'] = 1;
            $update_rs = $u->where($where)->save($data);
            if (! $update_rs)
            {
                E('更新标志位flag=1失败', 500);
            }
            
            $model->commit();
            
            $feed = new Feed();
            $feed->newFans($uid, $p_user['id']);
        } catch (\Exception $e)
        {
            $model->rollback();
            
            my_log("add fans fail:" . $e->getMessage() . " , " . $u->getLastSql() . " , " . $fans->getLastSql());
            
            return false;
        }
        
        return true;
    }

    public function getUserById($user_id)
    {
        $where = array();
        $where['id'] = $user_id;
        
        $data = $this->where($where)->find();
        if ($data)
        {
            $data['level_alias'] = $this->translateLevel($data['level']);
        }
        return $data;
    }

    public function getUsersByIds($user_ids)
    {
        if (empty($user_ids))
        {
            E('参数错误');
        }
        
        $where = array();
        $where['id'] = array(
            'IN',
            $user_ids
        );
        
        $data = $this->where($where)->select();
        if ($data)
        {
            foreach ($data as $key => $val)
            {
                $data[$key]['level_alias'] = $this->translateLevel($val['level']);
            }
        }
        return $data;
    }

    public function updateUserInfoByUid($uid)
    {
        $open_obj = new OpenId();
        $openid = $open_obj->uid2Openid($uid);
        if ($openid)
        {
            $info = $this->getWeixinUserDetailInfo($openid);
            if ($info)
            {
                $where = array();
                $where['id'] = $uid;
	       	   $rs = $this->where($where)->save($info);
	       	   if($rs!==false){
	       	       return true;	
	       	   }
	       }
	    }
	    
	    return false;
	}
	
}